<template>
  <div class="logs-container">
    <el-card class="logs-card">
      <template #header>
        <div class="card-header">
          <h2>运行日志</h2>
          <div class="header-actions">
            <el-button type="danger" size="small" @click="clearLogs">清空日志</el-button>
            <el-button type="primary" size="small" @click="refreshLogs">刷新</el-button>
          </div>
        </div>
      </template>
      
      <el-tabs v-model="activeTab">
        <el-tab-pane label="服务日志" name="service">
          <div class="tab-content">
            <div class="log-filter">
              <el-input
                v-model="logSearchKeyword"
                placeholder="搜索日志内容"
                clearable
                prefix-icon="el-icon-search"
                class="search-input"
              />
            </div>
            
            <div class="log-list" ref="logListRef">
              <div v-if="filteredLogs.length === 0" class="empty-logs">
                暂无日志记录
              </div>
              <div v-else class="log-items">
                <div 
                  v-for="(log, index) in filteredLogs" 
                  :key="index" 
                  class="log-item"
                >
                  <span class="log-time">{{ log.time }}</span>
                  <span class="log-content">{{ log.content }}</span>
                </div>
              </div>
            </div>
            
            <div class="log-actions">
              <el-checkbox v-model="autoScroll">自动滚动到底部</el-checkbox>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="错误日志" name="error">
          <div class="tab-content">
            <div class="log-filter">
              <el-input
                v-model="errorSearchKeyword"
                placeholder="搜索错误内容"
                clearable
                prefix-icon="el-icon-search"
                class="search-input"
              />
            </div>
            
            <div class="log-list" ref="errorListRef">
              <div v-if="filteredErrors.length === 0" class="empty-logs">
                暂无错误记录
              </div>
              <div v-else class="log-items">
                <div 
                  v-for="(error, index) in filteredErrors" 
                  :key="index" 
                  class="log-item error-item"
                >
                  <span class="log-time">{{ error.time }}</span>
                  <span class="log-content">{{ error.content }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="转发记录" name="forwarding">
          <div class="tab-content">
            <div class="log-filter">
              <el-input
                v-model="forwardingSearchKeyword"
                placeholder="搜索转发记录"
                clearable
                prefix-icon="el-icon-search"
                class="search-input"
              />
            </div>
            
            <div class="log-list">
              <div v-if="forwardingLogs.length === 0" class="empty-logs">
                暂无转发记录
              </div>
              <div v-else class="log-items">
                <div 
                  v-for="(log, index) in filteredForwardingLogs" 
                  :key="index" 
                  class="log-item forwarding-item"
                >
                  <span class="log-time">{{ log.time }}</span>
                  <div class="forwarding-content">
                    <div class="forwarding-source">
                      <span class="label">来源:</span> 
                      <span>{{ log.sourceGroup }} - {{ log.sourceUser }}</span>
                    </div>
                    <div class="forwarding-target">
                      <span class="label">目标:</span> 
                      <span>{{ log.targetUser }}</span>
                    </div>
                    <div class="forwarding-message">
                      <span class="label">消息:</span> 
                      <span>{{ log.message }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue';
import { useWechatStore } from '../store';
import { ElMessage, ElMessageBox } from 'element-plus';

const wechatStore = useWechatStore();
const activeTab = ref('service');
const logSearchKeyword = ref('');
const errorSearchKeyword = ref('');
const forwardingSearchKeyword = ref('');
const autoScroll = ref(true);
const logListRef = ref(null);
const errorListRef = ref(null);

// 模拟转发记录
const forwardingLogs = ref([
  {
    time: '2023-08-26 14:30:45',
    sourceGroup: '测试群组1',
    sourceUser: '用户A',
    targetUser: '用户B',
    message: '这是一条测试消息'
  },
  {
    time: '2023-08-26 15:20:10',
    sourceGroup: '测试群组2',
    sourceUser: '用户C',
    targetUser: '用户D',
    message: '这是另一条测试消息，内容较长，测试显示效果如何。这是另一条测试消息，内容较长，测试显示效果如何。'
  }
]);

// 过滤后的日志
const filteredLogs = computed(() => {
  if (!logSearchKeyword.value) return wechatStore.logs;
  return wechatStore.logs.filter(log => 
    log.content.toLowerCase().includes(logSearchKeyword.value.toLowerCase())
  );
});

// 过滤后的错误
const filteredErrors = computed(() => {
  if (!errorSearchKeyword.value) return wechatStore.errors;
  return wechatStore.errors.filter(error => 
    error.content.toLowerCase().includes(errorSearchKeyword.value.toLowerCase())
  );
});

// 过滤后的转发记录
const filteredForwardingLogs = computed(() => {
  if (!forwardingSearchKeyword.value) return forwardingLogs.value;
  const keyword = forwardingSearchKeyword.value.toLowerCase();
  return forwardingLogs.value.filter(log => 
    log.sourceGroup.toLowerCase().includes(keyword) ||
    log.sourceUser.toLowerCase().includes(keyword) ||
    log.targetUser.toLowerCase().includes(keyword) ||
    log.message.toLowerCase().includes(keyword)
  );
});

// 清空日志
function clearLogs() {
  ElMessageBox.confirm('确定要清空所有日志吗？此操作不可恢复。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    if (activeTab.value === 'service') {
      wechatStore.clearLogs();
    } else if (activeTab.value === 'error') {
      wechatStore.clearErrors();
    } else if (activeTab.value === 'forwarding') {
      forwardingLogs.value = [];
    }
    ElMessage.success('日志已清空');
  }).catch(() => {});
}

// 刷新日志
function refreshLogs() {
  ElMessage.success('日志已刷新');
}

// 监听日志变化，自动滚动到底部
watch(() => wechatStore.logs.length, () => {
  if (autoScroll.value && activeTab.value === 'service') {
    scrollToBottom(logListRef.value);
  }
});

watch(() => wechatStore.errors.length, () => {
  if (autoScroll.value && activeTab.value === 'error') {
    scrollToBottom(errorListRef.value);
  }
});

// 滚动到底部
function scrollToBottom(element) {
  if (!element) return;
  
  nextTick(() => {
    element.scrollTop = element.scrollHeight;
  });
}

// 组件挂载时
onMounted(() => {
  // 初始滚动到底部
  if (logListRef.value) {
    scrollToBottom(logListRef.value);
  }
  
  // 模拟添加日志
  const logInterval = setInterval(() => {
    if (wechatStore.isRunning) {
      wechatStore.addLog(`这是一条测试日志，时间: ${new Date().toLocaleTimeString()}`);
    }
  }, 5000);
  
  // 清理定时器
  onUnmounted(() => {
    clearInterval(logInterval);
  });
});
</script>

<style scoped>
.logs-container {
  max-width: 1000px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.tab-content {
  padding: 15px 0;
}

.log-filter {
  margin-bottom: 15px;
}

.search-input {
  max-width: 300px;
}

.log-list {
  height: 500px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  background-color: #f8f8f8;
}

.empty-logs {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
}

.log-items {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.log-item {
  padding: 8px;
  border-radius: 4px;
  background-color: #fff;
  display: flex;
  font-family: monospace;
  font-size: 14px;
  line-height: 1.5;
}

.error-item {
  background-color: #fef0f0;
  color: #f56c6c;
}

.forwarding-item {
  background-color: #f0f9eb;
  flex-direction: column;
}

.log-time {
  color: #909399;
  margin-right: 10px;
  white-space: nowrap;
}

.log-content {
  word-break: break-all;
  flex: 1;
}

.log-actions {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

.forwarding-content {
  display: flex;
  flex-direction: column;
  gap: 5px;
  margin-top: 5px;
}

.forwarding-source,
.forwarding-target,
.forwarding-message {
  display: flex;
}

.label {
  font-weight: bold;
  margin-right: 5px;
  width: 50px;
}
</style> 